import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Tcp 有连接 可靠传输 面向字节流 全双工
 */
public class TcpEchoServer {
    private ServerSocket serverSocket=null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket=new ServerSocket(port);
    }

    public void start() throws IOException{
        System.out.println("启动服务器");
        while(true){
            Socket clientSocket =serverSocket.accept();
            /*
            线程池
            ExecutorService service= Executors.newCachedThreadPool();
            for (int i = 0; i < 1000; i++) {
                service.submit(()->{
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });
            }
             */

            Thread t=new Thread(()->{
                try {
                    processConnection(clientSocket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            t.start();
        }
    }

    private void processConnection(Socket clientSocket) throws IOException{
        //打印日志，客户端信息
        System.out.printf("[%s,%d]客户端已上线！",clientSocket.getInetAddress(),clientSocket.getPort());
        //获取socket中持有的流对象
        try(InputStream inputStream=clientSocket.getInputStream();
            OutputStream outputStream=clientSocket.getOutputStream()){
        //为方便读取InputStream的请求，使用Scanner包装一下
            Scanner scanner=new Scanner(inputStream);
            PrintWriter printWriter=new PrintWriter(outputStream);

            while(true){
                //1.读取请求并解析
                if (!scanner.hasNext()){
                    //如果用scanner也无法读出数据，则说明与客户端连接断开
                    break;
                    //跳出循环
                }
                String request = scanner.next();

                //2.根据请求计算请求
                String response=process(request);

                // 3. 把响应写回给客户端
                // 此处可以按照字节数组直接来写, 也可以有另外一种写法.
                // outputStream.write(response.getBytes());
                printWriter.println(response);
                //存在缓冲区，因此要 flush
                printWriter.flush();

                //4.打印日志
                System.out.printf("[%s,%d] req=%S resp=%s",clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            System.out.printf("[%s,%d] 客户端已下线！",clientSocket.getInetAddress(),clientSocket.getPort());
            //要关闭资源
            clientSocket.close();
        }
    }

    private String process(String request){
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer=new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
